#!/bin/bash
#############################################
# author:fang
# version : v1.0
# name  : xfile
# dispcripe: just for video setting
# CopyRight@fangyunjiang[42550564@qq.com]
#############################################

source ~/command/common

_cur_dir="."
_tmp_file=_tmp_file_
_extname="jpg"
_oper=0

function swap_files_with_randow()
{
	local ts i files size file_no1 file_no2

	files=(`ls "$_cur_dir"/*.$_extname`)
	size=${#files[@]}
	ts=$(($1))

	for ((i=0; i<ts; i++));do
		file_no1=$(($RANDOM%$size))
		file_no2=$(($RANDOM%$size))
		while ((file_no1==file_no2));do
			file_no2=$(($RANDOM%$size))
		done
		mv ${files[$file_no1]} $_tmp_file
		mv ${files[$file_no2]} ${files[$file_no1]}
		mv $_tmp_file ${files[$file_no2]}
		echo "swap ${files[$file_no2]} ${files[$file_no1]} success"
	done
}

function set_file_to_index()
{
	local begin_num moved_num file_num index path file files size

	[ "$1" = "" ]&&begin_num=1||begin_num=$1
	moved_num=0
	file_num=0
	files=(`ls "$_cur_dir"/*.$_extname`)
	size=${#files[@]}

	for ((i=0; i<size; i++));do
		((index=begin_num+moved_num))
		path=$(dirname ${files[i]})
		file=$(basename ${files[i]})
		file_num=$((${file%%.*}))
		if ((file_num<=index && file_num>0));then
			echo "${files[i]} have exist"
			continue
		fi
		((moved_num++))
		if [ -f "$path/$index.$_extname" ];then
			echo "mv ${files[i]}  $path/$index.$_extname failed"
			((i--))
		else
			echo "mv ${files[i]}  $path/$index.$_extname sucess"
			mv "${files[i]}"  "$path/$index.$_extname"
		fi
	done
	echo "the next index is $((index+1))"
}

function add_files_to_index()
{
	local len start_num path oper
	local -a add_files
	start_num=1
	[ "$1" = "" ]&&path="."||path="$1"
	if ! [ -d "$path" ];then
		echo "$path is not exist"
		return
	fi
	if [ `__get_full_path  "$_cur_dir"` = `__get_full_path "$path"` ];then
		oper=mv
	else
		oper=cp
	fi

	add_files=(`ls "$path"/*.$_extname`)
	len=${#add_files[@]}

	for ((i=0; i<len; i++));do
		while [ -f "$_cur_dir/$start_num.$_extname" ];do
			((start_num++))
		done
		echo $oper "${add_files[i]}" "$_cur_dir/$start_num.$_extname"
		$oper "${add_files[i]}" "$_cur_dir/$start_num.$_extname"
	done
	echo "the last index is $((start_num-1))"
}

function classify_files_by_date()
{
	node -e " \
	const fs = require('fs-extra'); \
	const path = require('path'); \
	const moment = require('moment'); \
	function classifyFiles(dir, dist) { \
	    fs.readdirSync(dir).forEach(function(file, index) { \
	        const fullname = path.join(dir, file); \
	        const info = fs.statSync(fullname); \
	        const distdir = path.join(dist, moment(info.mtime).format('YYYY-MM-DD')); \
	        const distname = path.join(distdir, file); \
	        fs.ensureDirSync(distdir); \
	        fs.copySync(fullname, distname); \
	        console.log(distname+' 完成'); \
	    }); \
	} \
	classifyFiles('$1', '$2'); \
	"
}

function increase_filename_head_number()
{
	local addNumber fromNumber
	addNumber="${2%:*}"
	fromNumber="${2#*:}"
	if [ "$2" != "$addNumber:$fromNumber" ];then
		fromNumber="undefined"
	fi

	node -e " \
	const fs = require('fs-extra'); \
	const path = require('path'); \
	const _ = require('lodash'); \
	function main(dir, addNumber, fromNumber) { \
		let files = _.reject(_.sortBy(_.map(_.filter(fs.readdirSync(dir), o=>/.${_extname}$/.test(o)), o=>({ file: o, index: parseInt(o) })), o=>(addNumber>0?-1:1)*o.index), o=>fromNumber>0 ? o.index<=fromNumber : o.index>=-1*fromNumber); \
		files = _.map(_.filter(files, o=>!_.isNaN(o.index)), o=>({ fullname: path.join(dir, o.file), newFullName: path.join(dir, o.file.replace(o.index, o.index+addNumber)) })); \
		_.each(files, o=>fs.moveSync(o.fullname, o.newFullName)); \
		console.log('done'); \
	} \
	main('$1', $addNumber, $fromNumber); \
	"
}

function show_help()
{
	local -a list
	list="help"
	list=("${list[@]}" "Usage: xfile [OPTIONS]")
	list=("${list[@]}" "  -x [extname]: 设置后缀名，默认为：jpg")
	list=("${list[@]}" "  -p [cur_dir]: 设置当前目录，默认为：.")
	list=("${list[@]}" "  -w [n]: 交换当前目录后缀名为 extname 的文件n次")
	list=("${list[@]}" "  -s [start_num]: 当前目录后缀名为 extname 的文件从 start_num 起开始命名")
	list=("${list[@]}" "  -c [from_dir]: 将 from_dir 文件夹中后缀名为 extname 的文件拷贝到当前文件夹中并按顺序命名 ")
	list=("${list[@]}" "  -g [dist_dir]: 按照文件的修改日期将文件拷贝到相应的文件夹内 cur_dir->dist_dir/2021-01-01")
	list=("${list[@]}" "  -a [addNumber:fromNumber]:  将文件夹中后缀名为 extname 的文件形如: 1XX.jpg 的格式增加addNumber从fromNumber开始")
	list=("${list[@]}" "    xfile -x jpg -a 4: 11XX.jpg -> 15XX.jpg  8.jpg -> 13.jpg")
	list=("${list[@]}" "    xfile -x jpg -a -4: 所有的减去4")
	list=("${list[@]}" "    xfile -x jpg -a -4:-5: 小于5的减去4")
	list=("${list[@]}" "    xfile -x jpg -a -4:5: 大于5的减去4")
	list=("${list[@]}" "  -h: 查看帮助 ")
	__msgbox "${list[@]}"
}

function main()
{
	local ts start_num from_dir dist_dir
	while getopts :x:p:w:s:c:g:a: opt;do
		case $opt in
			x)_extname="$OPTARG";;
			p)_cur_dir="$OPTARG";;
			w)_oper=0;ts="$OPTARG";;
			s)_oper=1;start_num="$OPTARG";;
			c)_oper=2;from_dir="$OPTARG";;
			g)_oper=3;dist_dir="$OPTARG";;
			a)_oper=4;start_num="$OPTARG";;
			*)show_help;exit;;
		esac
	done

	[ -z "_cur_dir" ]&&_cur_dir="."

	case $_oper in
		0) swap_files_with_randow $ts;;
		1) set_file_to_index $start_num;;
		2) add_files_to_index "$from_dir";;
		3) classify_files_by_date "$_cur_dir" "$dist_dir";;
		4) increase_filename_head_number "$_cur_dir" "$start_num";;
	esac
}

main "$@"
